﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ChuanYe.Models;
using System.Data.Entity.Core.Objects;
using ChuanYe.IDAL;
using ChuanYe.Utils;

namespace ChuanYe.DAL
{
    public class NewsDAL:INewsDAL
    {
        /// <summary>
        /// 保存临时新闻信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool NewsTempCreate(NewsTemp model, NewsAttachs AttachModel)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                bool result = false;
                db.NewsTemp.Add(model);
                result= db.SaveChanges() > 0 ? true : false;
                if (AttachModel.FileName != null)
                {
                    AttachModel.NewsId = model.ID;
                    AttachModel.FileTitle = model.Title;
                    db.NewsAttachs.Add(AttachModel);
                    result = db.SaveChanges() > 0 ? true : false;
                }
                return result;
            }
        }
        /// <summary>
        /// 修改临时新闻信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool NewsTempUpdate(NewsTemp model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                NewsTemp NewsTempModel = new NewsTemp();
                if (model.CopyId == null)
                {
                    NewsTempModel = db.NewsTemp.FirstOrDefault(m => m.ID == model.ID);
                    NewsTempModel.IsCopy = true;
                    model.CopyId = model.ID;
                    model.ID = 0;
                    db.NewsTemp.Add(model);
                }
                else {
                    NewsTempModel = db.NewsTemp.FirstOrDefault(m => m.ID == model.ID);
                    NewsTempModel.Content = model.Content;
                    NewsTempModel.Title = model.Title;
                    NewsTempModel.PublishPerson = model.PublishPerson;
                    NewsTempModel.PublishDate = model.PublishDate;
                    NewsTempModel.PictureAddress = model.PictureAddress;
                }
                return db.SaveChanges() > 0 ? true : false;
            }
        }
        /// <summary>
        /// 保存新闻信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool NewsInfsCreate(NewsInfs model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                db.NewsInfs.Add(model);
                return db.SaveChanges() > 0 ? true : false;
            }
        }
        /// <summary>
        /// 修改新闻
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int NewsInfsUpdate(NewsInfs model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.NewsInfs.FirstOrDefault(m => m.ID == model.ID);
                if (Info != null)
                {
                    Info.Title = model.Title;
                    Info.PublishPerson = model.PublishPerson;
                    Info.PublishDate = model.PublishDate;
                    Info.NewsAttachId = model.NewsAttachId;
                    Info.Content = model.Content;
                }
                int i = db.SaveChanges();
                return i;
            }
        }
        /// <summary>
        /// 发布新闻
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int NewsInfsPublic(NewsInfs model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.NewsTemp.FirstOrDefault(m => m.ID == model.ID);
                if (Info != null)
                {
                    Info.IsChecked = true;
                }
                NewsInfs NewsInfsModel = new NewsInfs();
                NewsInfsModel.Content = Info.Content;
                NewsInfsModel.DepartmentId = Info.DepartmentId;
                NewsInfsModel.DepartmentName= Info.DepartmentName;
                NewsInfsModel.IsChecked = true;
                NewsInfsModel.NewsAttachId = Info.NewsAttachId;
                NewsInfsModel.NewsType = model.NewsType;
                NewsInfsModel.ParentID = model.ID;
                NewsInfsModel.PictureAddress= Info.PictureAddress;
                NewsInfsModel.PublishCode= Info.PublishCode;
                NewsInfsModel.PublishDate = Info.PublishDate;
                NewsInfsModel.PublishPerson= Info.PublishPerson;
                NewsInfsModel.Title= Info.Title;
                NewsInfsModel.UpLoadType = Info.UpLoadType;
                db.NewsInfs.Add(NewsInfsModel);
                int i = db.SaveChanges();
                //临时表附件FromType==2
                List<NewsAttachs> List = db.NewsAttachs.Where(m => m.NewsId == Info.ID && m.FromType==2).ToList();
                List<NewsAttachs> ListModel = new List<NewsAttachs>();
                if (List.Count() > 0)
                {
                    foreach (NewsAttachs item in List)
                    {
                        NewsAttachs modelAttach = new NewsAttachs();
                        modelAttach.NewsId = NewsInfsModel.ID;
                        modelAttach.FileName = item.FileName;
                        modelAttach.FilePath = item.FilePath;
                        modelAttach.FileSize = item.FileSize;
                        modelAttach.FileTitle = item.FileTitle;
                        modelAttach.FromType = 1;
                        ListModel.Add(modelAttach);
                    }
                    db.NewsAttachs.AddRange(ListModel);
                    db.SaveChanges();
                }
                return i;
            }
        }
       
        /// <summary>
        /// 根据ID获取单条临时新闻数据
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public NewsTempOneResult NewsTempGetByID(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                NewsTempOneResult result = new NewsTempOneResult();
                result.NewsTemp= db.NewsTemp.FirstOrDefault(m => m.ID == ID);
                result.NewsAttachsList = db.NewsAttachs.Where(m => m.NewsId == ID && m.FromType==2).ToList();
                return result;
            }
        }

        /// <summary>
        /// 根据ID获取单条已发布新闻数据
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public NewsInfs NewsInfsGetByID(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.NewsInfs.FirstOrDefault(m => m.ID == ID);
            }
        }

        /// <summary>
        /// 根据新闻ID获取附件列表
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public List<NewsAttachs> NewsAttachsGetByNewsID(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.NewsAttachs.Where(m => m.NewsId == ID && m.FromType==1).ToList();
            }
        }

        /// <summary>
        /// 删除临时新闻
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int NewsTempDelete(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.NewsTemp.FirstOrDefault(m => m.ID == ID);
                if (Info != null)
                {
                    db.NewsTemp.Remove(Info);
                }
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 删除新闻
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int NewsInfsDelete(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.NewsInfs.FirstOrDefault(m => m.ID == ID);
                if (Info != null)
                {
                    db.NewsInfs.Remove(Info);
                }

                //var newsTemp= db.NewsTemp.FirstOrDefault(m => m.ID == Info.ParentID);
                //newsTemp.IsChecked = false;

                int i = db.SaveChanges();
                return i;
            }
        }

        /// <summary>
        /// 保存新闻附件
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int NewsAttachsCreate(NewsAttachs model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                db.NewsAttachs.Add(model);
                db.SaveChanges();
                return model.ID;
            }
        }

        /// <summary>
        /// 保存新闻阅读状态表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool NewsReadStateCreate(NewsReadState model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                db.NewsReadState.Add(model);
                return db.SaveChanges() > 0 ? true : false;
            }
        }
        /// <summary>
        /// 分页查询临时新闻列表
        /// </summary>
        /// <param name="search"></param>
        /// <param name="Pager"></param>
        /// <returns></returns>
        public NewsTempListResult NewsTempGetList(NewsTempListSearch search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var TotalCountParameter = new ObjectParameter("TotalCount", typeof(int));
                List<SP_NewsTempList_Result> result=db.SP_NewsTempList(search.stateTime, search.endTime, search.DepId, search.DocType, search.IsChecked, Pager.rows, Pager.page, TotalCountParameter)
                                                     .OrderByDescending(o=>o.PublishDate).ToList();
                NewsTempListResult model = new NewsTempListResult();
                model.NewsTempList = result;
                model.totalRows= Convert.ToInt32(TotalCountParameter.Value);
                return model;


            }
        }
        /// <summary>
        /// 分页查询新闻列表
        /// </summary>
        /// <param name="search"></param>
        /// <param name="Pager"></param>
        /// <returns></returns>
        public NewsInfsResult NewsInfsGetList(NewsInfsSearch search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                NewsInfsResult result = new NewsInfsResult();
                result.totalRows = db.View_NewsInfs.Count();
                //var where = PredicateExtensionses.True<View_NewsInfs>();
                //where = where.And(p=>p.PublishDate >= search.stateTime);
                //where = where.And(p => p.PublishDate <= search.endTime);
                //where = where.And(p => p.DepartmentId == search.DptID);
                //where = where.And(p => p.IsChecked == (search.IsChecked == 1 ? false : true));
                //result.NewsInfsList=db.View_NewsInfs.Where(where)
                //               .OrderByDescending(m => m.PublishDate)
                //               .Skip(Pager.rows * (Pager.page - 1))
                //               .Take(Pager.rows)
                //               .ToList();
                result.NewsInfsList = db.View_NewsInfs.Where(
                     m => (search.stateTime == new DateTime() || m.PublishDate >= search.stateTime)
                     && (search.endTime == new DateTime() || m.PublishDate <= search.endTime)
                     && (search.DptID == 0 || m.DepartmentId == search.DptID)
                     && (search.IsChecked == 0 || m.IsChecked == (search.IsChecked == 1 ? false : true)))
                    .OrderByDescending(m => m.PublishDate)
                    .Skip(Pager.rows * (Pager.page - 1))
                    .Take(Pager.rows)
                    .ToList();
                return result;
            }
        }
        /// <summary>
        /// 获取已发布新闻列表
        /// </summary>
        /// <param name="search"></param>
        /// <param name="Pager"></param>
        /// <returns></returns>
        public NewsInfsResult NewsInfsPublicGetList(NewsInfsPublicSearch search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                NewsInfsResult result = new NewsInfsResult();

                var where = PredicateExtensionses.True<View_NewsInfs>();

                where = where.And(p=>p.PublishDate > search.stateTime);
                where = where.And(p => p.PublishDate < search.endTime);
                //if (search.DepId > 0)
                //{
                //    where = where.And(p => p.DepartmentId == search.DepId);
                //}
                if (search.NewsType > 0)
                {
                    where = where.And(p => p.NewsType== search.NewsType);
                }
                result.totalRows = db.View_NewsInfs.Where(where).Count();

                
                var list = db.View_NewsInfs.Where(where)
                    .Select(m => new {m.ID,m.Title,m.PublishDate,m.PublishCode,m.NewsType,m.PublishPerson,m.DepName,m.FilePath})
                    .OrderByDescending(m => m.PublishDate)
                    .Skip(Pager.rows * (Pager.page - 1))
                    .Take(Pager.rows)
                    .ToList();
                result.NewsInfsList = new List<View_NewsInfs>();
                foreach (var item in list)
                {
                    View_NewsInfs model = new View_NewsInfs();
                    model.ID = item.ID;
                    model.Title = item.Title;
                    model.PublishCode = item.PublishCode;
                    model.PublishDate = item.PublishDate;
                    model.NewsType = item.NewsType;
                    model.PublishPerson = item.PublishPerson;
                    model.DepName = item.DepName;
                    model.FilePath = item.FilePath;
                    result.NewsInfsList.Add(model);
                }
                return result;
            }
        }



        /// <summary>
        /// 获取已发布新闻列表
        /// </summary>
        /// <param name="search"></param>
        /// <param name="Pager"></param>
        /// <returns></returns>
        public NewsInfsResult NewsInfsPublicGetList2(NewsInfsPublicSearch search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                NewsInfsResult result = new NewsInfsResult();

                var where = PredicateExtensionses.True<View_NewsInfs>();

                where = where.And(p => p.PublishDate >= search.stateTime);
                where = where.And(p => p.PublishDate <= search.endTime);
                if (search.DepId > 0)
                {
                    where = where.And(p => p.DepartmentId == search.DepId);
                }
                if (search.NewsType > 0)
                {
                    where = where.And(p => p.NewsType == search.NewsType);
                }
                result.totalRows = db.View_NewsInfs.Where(where).Count();


                var list = db.View_NewsInfs.Where(where)
                    .Select(m => new { m.ID, m.Title, m.PublishDate, m.PublishCode, m.NewsType, m.PublishPerson, m.DepName, m.FilePath})
                    .OrderByDescending(m => m.PublishDate)
                    .Skip(Pager.rows * (Pager.page - 1))
                    .Take(Pager.rows)
                    .ToList();
                result.NewsInfsList = new List<View_NewsInfs>();
                foreach (var item in list)
                {
                    View_NewsInfs model = new View_NewsInfs();
                    model.ID = item.ID;
                    model.Title = item.Title;
                    model.PublishCode = item.PublishCode;
                    model.PublishDate = item.PublishDate;
                    model.NewsType = item.NewsType;
                    model.PublishPerson = item.PublishPerson;
                    model.DepName = item.DepName;
                    model.FilePath = item.FilePath;
                    result.NewsInfsList.Add(model);
                }
                return result;
            }
        }



        public List<dynamic> NewsInfsPublicGetListForGroup(NewsInfsPublicGroupSearch search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                List<dynamic> result = new List<dynamic>();
                if (search.NewsTypes == null || search.NewsTypes.Count == 0)
                {
                    search.NewsTypes = db.View_NewsInfs
                                      .GroupBy(g => g.NewsType).Select(s => s.Key.Value).Distinct().ToList();
                }
                foreach (var item in search.NewsTypes)
                {
                    List<View_NewsInfs> list = new List<View_NewsInfs>();
                    var where = PredicateExtensionses.True<View_NewsInfs>();
                    where = where.And(p => p.PublishDate > search.stateTime);
                    where = where.And(p => p.PublishDate < search.endTime);
                    //if (search.DepId > 0)
                    //{
                    //    where = where.And(p => p.DepartmentId == search.DepId);
                    //}

                    if (item == 3 || item == 7)
                    {
                        where = where.And(p => p.FilePath!=null);
                    }

                    where = where.And(p => p.NewsType == item);
                    var tempList= db.View_NewsInfs.Where(where)
                        .OrderByDescending(m => m.PublishDate)
                        .Select(m => new { m.ID, m.Title, m.PublishDate, m.PublishCode, m.NewsType, m.PublishPerson, m.DepName, m.FilePath, m.FileName })
                        .Skip(Pager.rows * (Pager.page - 1))
                        .Take(Pager.rows)
                        .ToList();
                    foreach (var data in tempList)
                    {
                        View_NewsInfs model = new View_NewsInfs();
                        model.ID = data.ID;
                        model.Title = data.Title;
                        model.PublishCode = data.PublishCode;
                        model.PublishDate = data.PublishDate;
                        model.NewsType = data.NewsType;
                        model.PublishPerson = data.PublishPerson;
                        model.DepName = data.DepName;
                        model.FilePath = data.FilePath;
                        model.FileName = data.FileName;
                        list.Add(model);
                    }
                    result.Add(new { NewsType = item, Data = list.OrderByDescending(m=>m.PublishDate) });
                }
                return result;
            }
        }


        /// <summary>
        /// 市局获取新闻信息统计
        /// </summary>
        /// <param name="search"></param>
        /// <param name="Pager"></param>
        /// <returns></returns>
        public NewsInfsStatisticsResult NewsInfsStatisticsGet(NewsInfsStatisticsSearch search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var TotalCountParameter = new ObjectParameter("TotalCount", typeof(int));
                List<SP_NewsInfsStatistics_Result> result = db.SP_NewsInfsStatistics(search.stateTime, search.endTime, Pager.rows, Pager.page, TotalCountParameter).ToList();
                NewsInfsStatisticsResult model = new NewsInfsStatisticsResult();
                model.NewsInfsList = result;
                model.totalRows = Convert.ToInt32(TotalCountParameter.Value);
                return model;
            }
        }
        /// <summary>
        /// 获取部门各信息类型数量统计
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public SP_NewsInfsStatisticsByDepId_Result NewsInfsStatisticsByDepIdGet(NewsInfsStatisticsByDepIdSearch search)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                SP_NewsInfsStatisticsByDepId_Result result = db.SP_NewsInfsStatisticsByDepId(search.stateTime, search.endTime, search.DepId)
                    .ToList()[0];
                return result;
            }
        }
        /// <summary>
        /// 获取部门各信息类型信息列表
        /// </summary>
        /// <param name="search"></param>
        /// <param name="Pager"></param>
        /// <returns></returns>
        public NewsInfsGetListByDepIdResult NewsInfsGetListByDepId(NewsInfsGetListByDepIdSearch search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var TotalCountParameter = new ObjectParameter("TotalCount", typeof(int));
                List<SP_NewsInfsGetListByDepId_Result> result = db.SP_NewsInfsGetListByDepId(search.stateTime, search.endTime, search.DepId,search.NewsType, Pager.rows, Pager.page, TotalCountParameter).ToList();
                NewsInfsGetListByDepIdResult model = new NewsInfsGetListByDepIdResult();
                model.NewsInfsList = result;
                model.totalRows = Convert.ToInt32(TotalCountParameter.Value);
                return model;
            }
        }
        /// <summary>
        /// 区县获取新闻信息统计
        /// </summary>
        /// <param name="search"></param>
        /// <param name="Pager"></param>
        /// <returns></returns>
        public SP_NewsInfsCountyStatistics_Result NewsInfsCountyStatisticsGet(NewsInfsCountyStatisticsSearch search)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                SP_NewsInfsCountyStatistics_Result result = db.SP_NewsInfsCountyStatistics(search.stateTime, search.endTime, search.DepId).ToList().FirstOrDefault();
                return result;
            }
        }


        public List<View_NewsTemp> NewTempGetList(View_NewsTemp info, GridPager2 pager)
        {
           
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var where = PredicateExtensionses.True<View_NewsTemp>();
                //剔除原稿
                where = where.And(p => p.IsCopy != true);

                //判定
                if (info.DepartmentId > 0)
                {
                    where = where.And(p => p.DepartmentId == info.DepartmentId);
                }

                if (info.DocType > 0)
                {
                    where = where.And(p => p.DocType == info.DocType);
                }

                if (info.IsChecked != null)
                {
                    where = where.And(p => p.IsChecked == info.IsChecked);
                }

                if (pager.StartTime != null)
                {
                    where = where.And(p => p.PublishDate >= pager.StartTime);
                    if (pager.EndTime != null)
                    {
                        where = where.And(p => p.PublishDate <= pager.EndTime);
                    }
                }

                if (pager.StartRow == 0)
                {
                    pager.StartRow = pager.PageSize * (pager.PageIndex - 1);
                }
                var query=db.View_NewsTemp.Where(where);
                var list = query.OrderByDescending(o=>o.ID).Skip(pager.StartRow)
                                                   .Take(pager.PageSize).ToList();
                pager.TotalRows = query.Count();
                return list;
            }
        }
    }
}
